import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import './counter_provider.dart';
import './user_provider.dart';
import './cart_provider.dart';
import './location_provider.dart';

class AppProvider extends StatelessWidget {
  final Widget child;

  AppProvider({
    Key? key,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (BuildContext context) => CounterProvider(),
        ),
        ChangeNotifierProvider(
          create: (BuildContext context) => CartProvider(),
        ),
        ChangeNotifierProvider(
          create: (BuildContext context) => LocationProvider(),
        ),
        // 需要依赖的状态
        ChangeNotifierProxyProvider<CartProvider, UserProvider>(
          create: (BuildContext context) => UserProvider(),
          update: (
            BuildContext context,
            CartProvider cartProvider,
            UserProvider? userProvider,
          ) {
            final result =
                userProvider != null && userProvider.cartProvider != null
                    ? userProvider
                    : UserProvider(cartProvider: cartProvider);
            cartProvider.userProvider = result;
            return result;
          },
        ),
      ],
      child: child,
    );
  }
}
